/*
54. 螺旋矩阵
给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。
示例 1:
输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
*/

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  const result = []
  if (!matrix.length || !matrix[0].length) {
    return result
  }
  const left = 0
  const top = 0
  const right = matrix[0].length - 1
  const bottom = matrix.length - 1
  printMatrix(matrix, left, top, right, bottom, result)
  return result
}

/**
 * @param {number[][]} matrix
 * @param {number} left
 * @param {number} top
 * @param {number} right
 * @param {number} bottom
 * @param {number[]} result
 */
function printMatrix (matrix, left, top, right, bottom, result) {
  if (left > right || top > bottom) {
    return
  }
  // 在一行
  if (top === bottom) {
    while (left <= right) {
      result.push(matrix[top][left++])
    }
  } else if (left === right) {
    // 在一列
    while (top <= bottom) {
      result.push(matrix[top++][left])
    }
  } else {
    let m = top
    let n = left
    while (n < right) {
      result.push(matrix[m][n++])
    }
    while (m < bottom) {
      result.push(matrix[m++][n])
    }
    while (n > left) {
      result.push(matrix[m][n--])
    }
    while (m > top) {
      result.push(matrix[m--][n])
    }
    printMatrix(matrix, ++left, ++top, --right, --bottom, result)
  }
}

console.log(spiralOrder([
  [1, 2, 3],
  [8, 9, 4],
  [7, 6, 5]
]))
